#include "dialog.h"
#include "ui_dialog.h"
#include "global.h"

Dialog::Dialog(QStringList param, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    setFocusPolicy(Qt::StrongFocus); // 确保可以接收键盘事件

    QRect rect = parent->geometry();
    this->setWindowFlags(Qt::WindowStaysOnTopHint);
    int x = rect.width()/2 - this->width() /2;
    int y = rect.height()/2 - this->height()/2;
    this->move(x, y);

    if(param.size() < 2){
        param.clear();
        param.push_back("4");
        param.push_back("此对话框所需的参数获取失败！");
    }

    ui->labMsgicon->setFont(Global::IconFont);
    if(ui->WidBottom->isHidden())
        ui->WidBottom->setHidden(false);
    if(!ui->btnCancel->isHidden())
        ui->btnCancel->setHidden(true);
    ui->btnConfirm->setEnabled(true);
    ui->btnConfirm->setText("确认");
    msgtye = param.at(0).toInt();
    switch(msgtye){
    case 1: //success
        ui->labMsgicon->setText(QChar(0xf00e));
        break;
    case 2: //question
        if(param.size() > 2)
            QuestionResponse = param.at(2);
        ui->labMsgicon->setText(QChar(0xefca));
        ui->btnCancel->setHidden(false);
        break;
    case 3: //warning
        ui->labMsgicon->setText(QChar(0xf025));
        break;
    case 4: //error
        ui->labMsgicon->setText(QChar(0xef98));
        break;
    case 5: //auto/waiting
        ui->labMsgicon->setText(QChar(0xec87));
        ui->WidBottom->setHidden(true);
        break;
    default: //information
        ui->labMsgicon->setText(QChar(0xef4e));
        break;
    }
    //显示内容
    ui->labMsgcontent->setText(param.at(1));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::fnInitFormSlots(){
    isInitialization = true;
    connect(ui->btnMsgClose, &QPushButton::clicked, this, [=](){
        this->close();
    });
    connect(ui->btnCancel, &QPushButton::clicked, this, [=](){
        ui->btnMsgClose->click();
    });
    ui->btnConfirm->setDefault(true);
    connect(ui->btnConfirm, &QPushButton::clicked, this, [=](){
        if(msgtye == 2 && QuestionResponse != ""){
            QStringList param = {QuestionResponse};
            emit MGlobal::fnGetInstance()->CallInsidePageAction(param);
            param.clear();
            QuestionResponse = "";
        }
        this->close();
    });
}

void Dialog::mousePressEvent(QMouseEvent *e){
    if(e->button()==Qt::LeftButton)
        point=e->pos();
}

void Dialog::mouseMoveEvent(QMouseEvent *e){
    if(e->buttons()&Qt::LeftButton)
        move(e->pos()+pos()-point);
}

void Dialog::showEvent(QShowEvent*){
    if(!isInitialization)
        fnInitFormSlots();
}

// 响应回车键事件
void Dialog::keyPressEvent(QKeyEvent *e) {
    if (e->key() == Qt::Key_Enter) {
        ui->btnConfirm->click();
    } else  QWidget::keyPressEvent(e);
}
